package com.hktf.uilib.utils;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.widget.Toast;

import com.hktf.corelib.utils.CommUtils;
import com.hktf.corelib.utils.LogMds;
import com.hktf.uilib.R;
import com.hktf.uilib.utils.UriUtils;

import java.io.File;
import java.util.List;

public class ShareUtil {
    private Context context;

    public ShareUtil(Context context) {
        this.context = context;
    }


    /**
     * 分享文字
     *
     * @param packageName
     * @param content
     * @param title
     * @param subject
     */
    public void shareText(String packageName, String className, String content, String title, String subject) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_SEND);
        intent.setType("text/plain");
        //		if(null != className && null != packageName && !TextUtils.isEmpty(className) && !TextUtils.isEmpty(packageName)){
        //
        //		}else {
        //			if(null != packageName && !TextUtils.isEmpty(packageName)){
        //				intent.setPackage(packageName);
        //			}
        //		}
        if (stringCheck(className) && stringCheck(packageName)) {
            ComponentName componentName = new ComponentName(packageName, className);
            intent.setComponent(componentName);
        } else if (stringCheck(packageName)) {
            intent.setPackage(packageName);
        }

        intent.putExtra(Intent.EXTRA_TEXT, content);
        if (null != title && !TextUtils.isEmpty(title)) {
            intent.putExtra(Intent.EXTRA_TITLE, title);
        }
        if (null != subject && !TextUtils.isEmpty(subject)) {
            intent.putExtra(Intent.EXTRA_SUBJECT, subject);
        }
        intent.putExtra(Intent.EXTRA_TITLE, title);
        Intent chooserIntent = Intent.createChooser(intent, "分享到：");
        chooserIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        CommUtils.getContext().startActivity(chooserIntent);
    }

    /**
     * 分享网页
     */
    public void shareUrl(String packageName, String className, String content, String title, String subject) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_SEND);
        intent.setType("text/plain");
        //		if(null != className && null != packageName && !TextUtils.isEmpty(className) && !TextUtils.isEmpty(packageName)){
        //
        //		}else {
        //			if(null != packageName && !TextUtils.isEmpty(packageName)){
        //				intent.setPackage(packageName);
        //			}
        //		}
        //		if(stringCheck(className) && stringCheck(packageName)){
        //			ComponentName componentName = new ComponentName(packageName, className);
        //			intent.setComponent(componentName);
        //		}else if(stringCheck(packageName)){
        //			intent.setPackage(packageName);
        //		}

        intent.putExtra(Intent.EXTRA_TEXT, content);
        if (null != title && !TextUtils.isEmpty(title)) {
            intent.putExtra(Intent.EXTRA_TITLE, title);
        }
        if (null != subject && !TextUtils.isEmpty(subject)) {
            intent.putExtra(Intent.EXTRA_SUBJECT, subject);
        }
        intent.putExtra(Intent.EXTRA_TITLE, title);
        Intent chooserIntent = Intent.createChooser(intent, "分享到：");
        context.startActivity(chooserIntent);
    }

    /**
     * 分享文件
     */
    public void shareFile(String packageName, String className, File file) {
        if (file.exists()) {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
                String weiXinPath = findWeiXinPath();
                if (weiXinPath != null) {
                    File fileWeiXinTemp = new File(weiXinPath + "/" + file.getName());
                    if (fileWeiXinTemp.exists()) {
                        fileWeiXinTemp.delete();
                    }
                }
            }

            Uri uri = UriUtils.getUri(CommUtils.getContext(), file);
            LogMds.e("cdz", "uri=" + uri);
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_SEND);
            intent.setType("*/*");
            //			intent.setType(FileOpen.getMimeTypeFromFile(file));
            if (stringCheck(packageName) && stringCheck(className)) {
                intent.setComponent(new ComponentName(packageName, className));
            } else if (stringCheck(packageName)) {
                intent.setPackage(packageName);
            }
            intent.putExtra(Intent.EXTRA_STREAM, uri);

            List<ResolveInfo> resInfoList = CommUtils.getContext().getPackageManager()
                    .queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
            for (ResolveInfo resolveInfo : resInfoList) {
                String packageName1 = resolveInfo.activityInfo.packageName;
                CommUtils.getContext().grantUriPermission(packageName1, uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
            }

            Intent chooserIntent = Intent.createChooser(intent, "分享到:");
            chooserIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            CommUtils.getContext().startActivity(chooserIntent);
        } else {
            //			Toast.makeText(context, "文件不存在", 1000).show();
        }
    }
    private String findWeiXinPath() {
        String root=android.os.Environment.getExternalStorageDirectory().getAbsolutePath();
        String wxPath1 = root + "/Android/data/com.tencent.mm/MicroMsg/Download";
        String wxPath2 = root + "/tencent/MicroMsg/Download";
        if (new File(wxPath1).exists()) {
            return wxPath1;
        }
        if (new File(wxPath2).exists()) {
            return wxPath2;
        }
        return null;
    }

    /**
     * 分享图片
     */
    public void shareImg(String packageName, String className, File file) {
        if (file.exists()) {
            Uri uri = Uri.fromFile(file);
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_SEND);
            intent.setType("image/*");
            if (stringCheck(packageName) && stringCheck(className)) {
                intent.setComponent(new ComponentName(packageName, className));
            } else if (stringCheck(packageName)) {
                intent.setPackage(packageName);
            }
            intent.putExtra(Intent.EXTRA_STREAM, uri);
            Intent chooserIntent = Intent.createChooser(intent, "分享到:");
            context.startActivity(chooserIntent);
        } else {
            //			Toast.makeText(context, "文件不存在", 1000).show();
        }
    }

    /**
     * 分享音乐
     */
    public void shareAudio(String packageName, String className, File file) {
        if (file.exists()) {
            Uri uri = Uri.fromFile(file);
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_SEND);
            intent.setType("audio/*");
            if (stringCheck(packageName) && stringCheck(className)) {
                intent.setComponent(new ComponentName(packageName, className));
            } else if (stringCheck(packageName)) {
                intent.setPackage(packageName);
            }
            intent.putExtra(Intent.EXTRA_STREAM, uri);
            Intent chooserIntent = Intent.createChooser(intent, "分享到:");
            context.startActivity(chooserIntent);
        } else {
            //			Toast.makeText(context, "文件不存在", 1000).show();
        }
    }

    /**
     * 分享视频
     */
    public void shareVideo(String packageName, String className, File file) {
        setIntent("video/*", packageName, className, file);
    }

    public void setIntent(String type, String packageName, String className, File file) {
        if (file.exists()) {
            Uri uri = Uri.fromFile(file);
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_SEND);
            intent.setType(type);
            if (stringCheck(packageName) && stringCheck(className)) {
                intent.setComponent(new ComponentName(packageName, className));
            } else if (stringCheck(packageName)) {
                intent.setPackage(packageName);
            }
            intent.putExtra(Intent.EXTRA_STREAM, uri);
            Intent chooserIntent = Intent.createChooser(intent, "分享到:");
            context.startActivity(chooserIntent);
        } else {
            //			Toast.makeText(context, "文件不存在", 1000).show();
        }
    }

    /**
     * 分享多张图片和文字至朋友圈
     *
     * @param title
     * @param packageName
     * @param className
     * @param file        图片文件
     */
    public void shareImgToWXCircle(String title, String packageName, String className, File file) {
        if (file.exists()) {
            Uri uri = Uri.fromFile(file);
            Intent intent = new Intent();
            ComponentName comp = new ComponentName(packageName, className);
            intent.setComponent(comp);
            intent.setAction(Intent.ACTION_SEND);
            intent.setType("image/*");
            intent.putExtra(Intent.EXTRA_STREAM, uri);
            intent.putExtra("Kdescription", title);
            context.startActivity(intent);
        } else {
            Toast.makeText(context, "文件不存在", Toast.LENGTH_LONG).show();
        }


    }

    /**
     * 是否安装分享app
     *
     * @param packageName
     */
    public boolean checkInstall(String packageName) {
        try {
            context.getPackageManager().getPackageInfo(packageName, PackageManager.GET_ACTIVITIES);
            return true;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
            //			Toast.makeText(context, "请先安装应用app", 1500).show();
            return false;
        }
    }

    /**
     * 跳转官方安装网址
     */
    public void toInstallWebView(String url) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(url));
        context.startActivity(intent);
    }

    public boolean stringCheck(String str) {
        if (null != str && !TextUtils.isEmpty(str)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 调用shareSdk分享
     *
     * @param url
     */
    //调用分享
    public void showShare(String url) {
        if (true) {
//        if ("YDS-C20-Android".equals(Config.CLIENTNAME)) {
            shareText(null, null, url, CommUtils.getString(R.string.app_name) + R.string.dia_report_share, null);
            return;
        }
        //		MobSDK.init(CommUtils.getContext());
//        OnekeyShare oks = new OnekeyShare();
//
//        //关闭sso授权
//        oks.disableSSOWhenAuthorize();
//        // 分享时Notification的图标和文字  2.5.9以后的版本不调用此方法
//        //oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name));
//        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
//        oks.setTitle(CommUtils.getString(R.string.app_name) + R.string.dia_report_share);//"诊断报告分享"
//        // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
//        oks.setTitleUrl(url);
//        // text是分享文本，所有平台都需要这个字段
//        oks.setText(CommUtils.getString(R.string.app_name) + R.string.dia_report_share + url);
//        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
//        // oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
//        // url仅在微信（包括好友和朋友圈）中使用
//        oks.setUrl(url);
//        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
//        oks.setComment(CommUtils.getString(R.string.app_name) + R.string.dia_report_comment);
//        // site是分享此内容的网站名称，仅在QQ空间使用
//        oks.setSite(CommUtils.getString(R.string.app_name));
//        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
//        oks.setSiteUrl(url);
//        // 启动分享GUI
//        oks.show(MobSDK.getContext());

    }
}